<?php

class code{
	private $str_code = "abcdefghjkmnpqrstuvwxy23456789";//随机因子
	private $code;//验证码
	private $_maxlength;//验证码长度
	private $_width = 120;
	private $_height = 50;
	private $_img;//图像句柄
	private $fontSize = 25;//字体大小
	private $fontColor;//字体颜色
	private $font;

	public function __construct($_maxlength,$_width=120,$_height=50){
		$this->_maxlength = $_maxlength;
		$this->_width = $_width;
		$this->_height = $_height;
		$this->font = dirname(__FILE__).'\arial.ttf';
		
	}

	/**
	*
	*生成随机码
	*
	*/
	public function createCode(){

		$_len = strlen($this->str_code)-1;
		for($i = 0;$i < $this->_maxlength;$i++){
			$this->code .= $this->str_code[rand(0,$_len)];
		}
	}
	/**
	*
	*创建背景
	*
	*/
	public function createbackGround(){
		$this->_img = imagecreatetruecolor($this->_width,$this->_height);
		$color = imagecolorallocate($this->_img, mt_rand(157,255),mt_rand(157,255),mt_rand(157,255));
		imagefilledrectangle($this->_img, 0, $this->_height, $this->_width, 0, $color);

	}

	/**
	*
	*输出文字
	*
	*/
	public function createFont(){
		$_x = $this->_width / $this->_maxlength;
		for($i = 0;$i < $this->_maxlength;$i++){
			$this->fontColor = imagecolorallocate($this->_img, mt_rand(0,156), mt_rand(0,156), mt_rand(0,156));
			imagettftext($this->_img,$this->fontSize,mt_rand(-30,30),$_x*$i+mt_rand(3,5),$this->_height / 1.4,$this->fontColor,$this->font,$this->code[$i]);
		}
	}
	//生成干扰
	public function createLine(){
		//线条
		for($i=0;$i<5;$i++){
			$color = imagecolorallocate($this->_img, mt_rand(0,156),mt_rand(0,156),mt_rand(0,156));
			imageline($this->_img, mt_rand(0,$this->_width), mt_rand(0,$this->_height), mt_rand(0,$this->_width), mt_rand(0,$this->_height),$color);
		}

		//雪花
		for($i=0;$i<10;$i++){
			$color = imagecolorallocate($this->_img, mt_rand(0,200),mt_rand(0,200),mt_rand(0,200));
			imagestring($this->_img,mt_rand(1,5), mt_rand(0,$this->_width),mt_rand(0,$this->_height),'*', $color);
		}

	}

	/**
	*
	*输出图像
	*
	*/
	public function outputImg(){
		header('Content-type:image/png');
		imagepng($this->_img);
		imagedestroy($this->_img);
	}
	
	public function start(){
		$this->createCode();
		$this->createbackGround();
		$this->createFont();
		$this->createLine();
		$this->outputImg();
	}
	
	public function getCode(){
		return strtolower($this->code);
	}
	
}


?>